//
//  LYZOAuthViewController.m
//  柳州微博
//
//  Created by Apple_Lzzy40 on 16/9/29.
//  Copyright © 2016年 Apple_Lzzy40. All rights reserved.
//

#import "ZQOAuthViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "ZQAccount.h"
#import "ZQViewController.h"
#import "ZQNewfeatureViewController.h"
#import "UIWindow+ZQExtension.h"
#import "ZQAccountTool.h"
#import "ZQUser.h"
@interface ZQOAuthViewController ()<UIWebViewDelegate>

@end

@implementation ZQOAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //1.创建一个WebView
    UIWebView * webView=[[UIWebView alloc] init];
    
    webView.frame=self.view.bounds;
    webView.delegate=self;
    
    [self.view addSubview:webView];
    
    //2.加载页面地址
       NSURL * url=[NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=3690659434&redirect_uri=http://www.qq.com"];
    NSURLRequest * request=[NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}
//监控所加载的请求页面，即将加载前的方法
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
       //1.获取URL
    NSString * url=request.URL.absoluteString;
    NSRange range=[url rangeOfString:@"code="];
    //有Code存在
    NSLog(@"%@", url);
    if (range.length>0) {
        NSUInteger fromIndex=range.location+ range.length;
        NSString *code=[url substringFromIndex:fromIndex];
       // NSLog(@"code =%@",code);
        if (code.length>0) {
            //利用用户授权后的Code曲获取access_toke
            [self accessTokeWithCode:code];
        }
    }
    return YES;
}

-(void)accessTokeWithCode:(NSString *)code
{
   /*
    App Key：3690659434
    App Secret：e9235d155b25dac00e562fa2cfb3a907 
    client_id	true	string	申请应用时分配的AppKey。
    redirect_uri	true	string	授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址。
    scope	false	string	申请scope权限所需参数，可一次申请多个scope权限，用逗号分隔。使用文档
    */
 //1.创建管理者
    AFHTTPRequestOperationManager * manager=[AFHTTPRequestOperationManager manager];
    //2.设置参数
    NSMutableDictionary * params=[NSMutableDictionary dictionary];
    
    params[@"client_id"]=@"3690659434";
    params[@"client_secret"]=@"e9235d155b25dac00e562fa2cfb3a907";
    params[@"grant_type"]=@"authorization_code";
    params[@"code"]=code;
    params[@"redirect_uri"]=@"http://www.qq.com";
    
    //3.发送请求
    [manager POST:@"https://api.weibo.com/oauth2/access_token" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
        
        //2.将返回的数据转成Model
       ZQAccount * account = [ZQAccount accountWithDict:responseObject];
        
        [self setUpserInfo:account];
        //保存账号信息
        [ZQAccountTool saveAccount:account];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@" 请求失败%@",error);

    }];
     //来到此地，帐号信息以存
    //获取主窗口，再切换窗口
//    UIWindow * window=[UIApplication sharedApplication].keyWindow;
//    [window switchRootViewController];
    

}

/**获取服务器的用户信息（昵称）*/
-(void)setUpserInfo:(ZQAccount *)account
{
    //1.创建管理者
    AFHTTPRequestOperationManager * manager=[AFHTTPRequestOperationManager manager];
    //2.设置参数
    NSMutableDictionary * params=[NSMutableDictionary dictionary];
    
    //创建帐号实例
//    ZQAccount * account =[ZQAccountTool account];
    params[@"access_token"]=account.access_token;
    params[@"uid"]=account.uid;
    //3.发送请求https://api.weibo.com/2/users/show.json
    [manager GET :@"https://api.weibo.com/2/users/show.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
        
        //  NSLog(@" 请求成功 返回数据%@",responseObject);
        
        //        //从返回数据获取微博账号的名称
        //        NSString * name = responseObject[@"name"];
        ZQUser * user=[ZQUser objectWithKeyValues:responseObject];
        NSString * name=user.name;
        
        //把名称赋给帐号模型
        NSLog(@"%@",name);
        account.name=user.name;
        
        //调用保存方法
        [ZQAccountTool saveAccount:account];
        
        UIWindow * window = [UIApplication sharedApplication].keyWindow;
        [window switchRootViewController];

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@" 请求失败%@",error);
        
    }];
}

/*   授权过程
 1.获取的应用程序的AppKey 和AppSecret:通过注册微博,并成为开发者，然后创建移动应用
 
 2.获取用户授权的Code:通过加载用户授权页面（参数：AppKey）用户授权后，服务器返回Code

 3.获取最终访问Token：通过加载access_toke请求（AppKey 、AppSecret、Code）服务器验证后返回access_toke
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
